from sqlalchemy.orm import Session

from app.crud import file_info_service
from app.models.category import CategoryDo
from app.schemas.category import CategoryVo


def category_list(db: Session) -> list[CategoryVo]:
    """查询分类"""
    category_do_list = db.query(CategoryDo).filter(CategoryDo.status == 1).all()

    # 查询图片
    image_ids: list[int] = []
    for category_do in category_do_list:
        if category_do.image_id:
            image_ids.append(category_do.image_id)
    file_dict = file_info_service.query_file_ids(db, image_ids)
    # 转换类型
    vo_map: dict[int, CategoryVo] = {
        cat.category_id: CategoryVo.model_validate(
            cat, update={'image': file_dict.get(cat.image_id)}
        )
        for cat in category_do_list
    }
    return build_category_tree(vo_map)


def build_category_tree(vo_map: dict[int, CategoryVo]) -> list[CategoryVo]:
    """
    组装成树
    """
    roots: list[CategoryVo] = []
    for vo in vo_map.values():
        if vo.parent_id == 0:
            roots.append(vo)
        else:
            parent = vo_map.get(vo.parent_id)
            if parent:
                parent.children.append(vo)
    return roots
